<template>
  <div style="border: 1px solid #ccc">
    <Toolbar style="border-bottom: 1px solid #ccc" :editor="editorRef" :defaultConfig="toolbarConfig" :mode="mode" />
    <Editor style="height: 400px; overflow-y: hidden;" v-model="valueHtml" :defaultConfig="editorConfig" :mode="mode"
      @onCreated="handleCreated" />
  </div>
</template>
<script lang='ts' setup>
import { shallowRef, ref, onBeforeUnmount, computed } from 'vue';
import '@wangeditor/editor/dist/css/style.css'; // 引入 css
import { Editor, Toolbar } from '@wangeditor/editor-for-vue';

let emit = defineEmits(['update:modelValue'])
let props = defineProps({
  modelValue: String,
})

const editorRef = shallowRef();
const toolbarConfig = ref({});
const editorConfig = ref({ placeholder: '请输入内容...' });
const mode = 'default';

// 保存editor实例
const handleCreated = (editor: any) => {
  editorRef.value = editor; // 记录 editor 实例，重要！
}

// 子组件和父组件同步html值
const valueHtml = computed({
  get() {
    return props.modelValue
  },
  set(val) {
    // 防止富文本内容为空时，校验失败
    if (editorRef.value.isEmpty()) val = "";
    emit('update:modelValue', val)
  }
})
// 销毁editor实例
onBeforeUnmount(() => {
  const editor = editorRef.value;
  if (editor == null) return;
  editor.destroy();
})
</script>
<style lang='less' rel='stylesheet/less' scoped>

</style>